package common

import (
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/http_server/controller"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/errcode"
	profitRepo "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/base/profit"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/service/base/profit"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
	"time"
)

type ProfitController struct {
	controller.BaseController
	profitService profit.ProfitServiceIface
}

func NewProfitController(
	profitService profit.ProfitServiceIface,
) *ProfitController {
	return &ProfitController{
		profitService: profitService,
	}
}

func (c *ProfitController) RegisterRouter(g *gin.RouterGroup) {
	g.POST("/sync-profit", c.syncProfit)
}

type syncProfitRequest struct {
	ProfitGuid      string `json:"profit_guid"`
	DeliveryNo      string `json:"delivery_no"`
	DeliveryBatchNo string `json:"delivery_batch_no"`
	DeliveryAuthId  string `json:"delivery_auth_id"`
	StartTime       string `json:"start_time" binding:"required"`
	EndTime         string `json:"end_time" binding:"required"`
	ProductCode     string `json:"product_code" binding:"required,oneof=MarketReport ClueRadarNationwide ClueRadarProvince UserAccount"`
	Number          int32  `json:"number"`
	OperatorGuid    string `json:"operator_guid"`
	OperatorName    string `json:"operator_name"`
}

func (c *ProfitController) syncProfit(ctx *gin.Context) {
	request := &syncProfitRequest{}
	if err := ctx.ShouldBind(request); err != nil {
		stark.Logger.Errorf(ctx, "同步租户出库权益记录失败,参数错误,syncProfit request:%+v, err:%s", request, err.Error())
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "参数错误")
		return
	}
	st, err1 := time.ParseInLocation("2006-01-02 15:04:05", request.StartTime, time.Local)
	et, err2 := time.ParseInLocation("2006-01-02 15:04:05", request.EndTime, time.Local)
	if err1 != nil || err2 != nil {
		stark.Logger.Errorf(ctx, "同步租户出库权益记录失败,租期时间格式错误,syncProfit request:%+v, err1:%+v, err2:%+v", request, err1, err2)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "租期时间格式错误")
		return
	}
	err := c.profitService.SyncProfit(ctx, &profitRepo.GfyxProfitPo{
		Id:              0,
		ProfitCode:      request.ProductCode,
		StartTime:       st,
		EndTime:         et,
		Number:          request.Number,
		DeliveryBatchNo: request.DeliveryBatchNo,
		DeliveryNo:      request.DeliveryNo,
		DeliveryAuthId:  request.DeliveryAuthId,
		ProfitGuid:      request.ProfitGuid,
		CreatedOn:       time.Now(),
		CreatedBy:       request.OperatorGuid,
		ModifiedOn:      time.Now(),
		ModifiedBy:      request.OperatorGuid,
		IsDeleted:       0,
	})
	if err != nil {
		stark.Logger.Errorf(ctx, "同步租户出库权益记录失败,syncProfit request:%+v, err:%+s", request, err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}
	stark.Logger.Infof(ctx, "同步租户出库权益记录成功,syncProfit request:%+v", request)

	c.Success(ctx, "ok")
}
